package com.qh.yyxt.controller;

import com.qh.yyxt.pojo.entity.thing.Thing;
import com.qh.yyxt.mapper.ThingMapper;
import com.qh.yyxt.utils.QrCodeUtils;
import com.qh.yyxt.utils.ZipUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
public class QrCodeController {
    @Autowired
    private ThingMapper thingMapper;
    @GetMapping("/user/downzip")
    @ResponseBody
    public void packageFileToZip(HttpServletRequest request,HttpServletResponse response) throws IOException {
        List<Thing> things = thingMapper.selectList(null);
        List<String> signs = new ArrayList<>();
        for(Thing t:things){
            if(t.getSign()==null||t.getSign().equals("")) continue;
            for(String s:t.getSign().split(" ")){
                signs.add(s);
            }
        }
        System.out.println(signs.toString());

        List<File> fileList = new ArrayList<>();
        for (String sign : signs) {
//            String s = "/QrCode/img/"+sign+".png";
            String s = "C:/ewm/"+sign+".png"; //图片路径
            try {

                QrCodeUtils.exportQuickResponseCode(request,response,sign);

            } catch (Exception e) {
                e.printStackTrace();
            }
            File file = new File(s);
            fileList.add(file);
        }
        // 先在D盘创建一个压缩包
        String uuid = UUID.randomUUID().toString().replace("-", "");
//        File zipFile = new File("/QrCode/package/"+uuid+".zip");//生成zip路径
       File zipFile = new File("C:/"+uuid+".zip");
        // 将package.zip的File对象传到toZip对象中
        ZipUtils.toZip(fileList, zipFile);
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment;filename=" +uuid+".zip" );
        FileInputStream fileInputStream = new FileInputStream(zipFile);
        OutputStream out = response.getOutputStream();
        int len = 0;
        byte[] by = new byte[1024*1024];
        while ((len = fileInputStream.read(by))>0){
            out.write(by,0,len);
        }
        out.close();
        ZipUtils.delFile(zipFile);//删除文件
    }
}
